<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>serverOne</title>
    <style>
      iframe {
        border: 1px solid #000;
        margin-top: 10px;
      }
    </style>
  </head>
  <body>
    <div>
      我是serverOne
      <button id="btn">给子页面传值</button>
    </div>
    <iframe src="http://127.0.0.1:3400/" frameborder="0" id="iframe"></iframe>

    <script>
      window.onload = function () {
        const iframe = document.getElementById("iframe");
        const btn = document.getElementById("btn");

        btn.onclick = function () {
          //通过postMessage跨域
          iframe.contentWindow.postMessage(
            "我是serverOne",
            "http://127.0.0.1:3400"
          );
        };

        function receiveMessage(event) {
          // 我们能相信信息的发送者吗?  (也许这个发送者和我们最初打开的不是同一个页面).
          if (event.origin !== "http://127.0.0.1:3400") return;
          btn.innerText = event.data;
        }

        window.addEventListener("message", receiveMessage, false);
      };
    </script>
  </body>
</html>
